﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iAnywhere.Data.SQLAnywhere;
using System.Configuration;
using Oracle.DataAccess.Client;

namespace T_Performance.Service
{
    public static class ClearTempBppmData
    {
        public static void ClearDataByTime() 
        {
            var fromtime = GetUnixTimestamp();
            string bppmConn = string.Empty;

            foreach (var bppmConnkey in ConfigurationManager.AppSettings)
            {
                if (bppmConnkey.ToString().Contains("烟草专卖局"))
                {
                    bppmConn = ConfigurationManager.AppSettings[bppmConnkey.ToString()];

                    try
                    {
                        DeleteDataFromLastDate(fromtime, bppmConn);
                    }
                    catch (Exception ex)
                    {
                        SysLog.WriteSysLog(bppmConnkey.ToString());
                        SysLog.WriteSysLog(ex.ToString());
                        continue;
                    }
                }
            }
        }

        public static void ClearT_PerformanceByTime(string itPortal)
        {
            var fromtime = GetUnixTimestamp();
            string sql = "Delete from t_performance where fromtime > " + fromtime;
            using (OracleConnection conn = new OracleConnection(itPortal))
            { 
                try
                {
                    conn.Open();
                    OracleCommand cmd = new OracleCommand(sql, conn);
                    int ret = cmd.ExecuteNonQuery();
                    cmd.Dispose();
                    conn.Close();
                }
                catch (Exception ex)
                {
                    SysLog.WriteSysLog(ex.ToString());
                }
            }
        }

        public static Decimal GetUnixTimestamp()
        {
            int IDate = Convert.ToInt32(ConfigurationManager.AppSettings["ClearDate"]);
            string str_Date = DateTime.Now.AddDays(IDate).ToShortDateString();
            Console.WriteLine("Begin to get unix timestamp by " + str_Date);
            Console.WriteLine("Clear Date > " + str_Date + "  Data....");
            DateTime dDate = Convert.ToDateTime(str_Date);
            return ((dDate.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
        }

        public static void DeleteDataFromLastDate(decimal fromtime, string bppmStr)
        {
            string sql = "Delete from t_performance where fromtime > " + fromtime;
            using (SAConnection conn = new SAConnection(bppmStr))
            {
                conn.Open();
                SACommand cmd = new SACommand(sql, conn);
                int ret = cmd.ExecuteNonQuery();
                cmd.Dispose();
                conn.Close();
            }
        }
    }
}
